package com.espirit.file;

import java.io.IOException;
import java.nio.file.FileSystems;
import java.nio.file.FileVisitResult;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.SimpleFileVisitor;
import java.nio.file.attribute.BasicFileAttributes;
import java.util.LinkedHashSet;
import java.util.Set;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;



public class FileScanner {
	
	private static final Logger logger =  LoggerFactory.getLogger(FileScanner.class);

	private FileScanner(){
	}
	
	public static Set<NFile> scan(String dir) throws IOException{
		Path path = FileSystems.getDefault().getPath(dir);
		return scan(path);
	}
	
	public static Set<NFile> scan(Path path) throws IOException{
		return scan(path, false);
	}
	
	public static Set<NFile> scan(Path path ,final Boolean ignoreSubDir) throws IOException{
		final Set<NFile> pathes = new LinkedHashSet<NFile>(500);
		Files.walkFileTree(path, new SimpleFileVisitor<Path>(){
			
			@Override
			public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
				Path absolutePath = Files.isSymbolicLink(file) ? file.toRealPath() : file.toAbsolutePath();
				pathes.add(new NFile(absolutePath,attrs));
				logger.info("Visit file :" + file.toString()+"\t lastUpdateTime : " + attrs.lastModifiedTime());
				return FileVisitResult.CONTINUE;
			}
			
			@Override
			public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs) throws IOException {
				logger.info("Visit directory :" + dir.toString());
				FileVisitResult result;
				if (!dir.equals(path) && ignoreSubDir) {
					result = FileVisitResult.SKIP_SUBTREE;
				}else {
					result = FileVisitResult.CONTINUE;
				}
				return result;
			}
		});
		
		return pathes;
	}
}
